﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.HtmlControls;
using System.Web;

namespace Kiiro.SiteDefinition.PortalPages
{
    public partial class ActiveProjects : BasePage
    {
        public Pager V2Pager
        {
            get { return ( Pager ) v2Pager; }
        }

        public WelcomeMessagePanel V2WelcomeMessagePanel
        {
            get { return ( WelcomeMessagePanel ) v2WelcomeMessagePanel; }
        }

        public Filter Filter
        {
            get { return ( Filter ) v2Filter; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        private List<Project> projects = new List<Project> ( );
        public List<Project> Projects
        {
            get { return projects; }
            set { projects = value; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            litTitle.Text = "Active Projects";

            AddCommandButtons ( );

            if ( PermissionBitsProjects [ 1 ] )
            {
                V2Pager.NextClick += new EventHandler ( RePopulatePage );
                V2Pager.PrevClick += new EventHandler ( RePopulatePage );
                V2Pager.EntitiesPerPageChange += new EventHandler ( RePopulatePage );

                Projects = ProjectsModel.GetProjectsForUser ( SiteCollectionId, ServerRelativeUrl, CurrentUser, new List<ProjectStatus> ( ) { ProjectStatus.Active } );
                Projects.ForEach ( x => x.CustomFieldNamesAndValues = CustomModel.HarvestCustomFields ( typeof ( Project ), x.Id, HttpContext.Current, SiteCollectionId, ServerRelativeUrl ) );

                Filter.EntityType = EntityType.Project;
                Filter.Entities = Projects.Cast<BaseEntity> ( ).ToList ( );
                Projects = Filter.Apply ( ).Cast<Project> ( ).ToList ( );

                PopulatePage ( );

                if ( IsPostBack )
                    V2Pager.DisplayedCount = lnkShowProjectDetails.Text == "Show Project Details" ?
                        rptProject.Items.Count : ProjectSummaryRepeater.Items.Count;
            }
            else
            {
                v2WelcomeMessagePanel.Visible = true;
                V2WelcomeMessagePanel.ShowPanel = true;
                V2WelcomeMessagePanel.ServerRelativeUrl = ServerRelativeUrl;
                V2WelcomeMessagePanel.ManageUsers = false;
                V2WelcomeMessagePanel.ShowHidePanel ( Constants.PagerEntity.Projects, PermissionBitsProjects );
                pnlProjectsList.Visible = false;
                actionBar.Visible = false;
                v2Pager.Visible = false;
            }
        }

        #region Page Related Methods

        internal void PopulatePage ( )
        {
            if ( Projects.Count > 0 || !string.IsNullOrEmpty ( Request.Params [ "Field" ] ) )
            {
                SortList ( );

                V2Pager.PopulatePager ( Projects.Count, Constants.PagerEntity.Projects );

                if ( lnkShowProjectDetails.Text == "Show Project Details" )
                {
                    ProjectSummaryRepeater.Visible = false;
                    pnlProjectsList.Visible = true;

                    rptProject.DataSource = Projects.GetRange ( V2Pager.PagingIndex, V2Pager.DisplayedCount );
                    rptProject.DataBind ( );

                    if ( rptProject.Items.Count > 0 )
                    {
                        HtmlTableRow trProject = ( HtmlTableRow ) rptProject.Items [ rptProject.Items.Count - 1 ].FindControl ( "trProject" );
                        trProject.Attributes.Add ( "class", "borderless" );
                    }
                }
                else
                {
                    ProjectSummaryRepeater.Visible = true;
                    pnlProjectsList.Visible = false;

                    ProjectSummaryRepeater.DataSource = Projects.GetRange ( V2Pager.PagingIndex, V2Pager.DisplayedCount );
                    ProjectSummaryRepeater.DataBind ( );
                }
            }
            else
            {
                v2Pager.Visible = false;

                v2WelcomeMessagePanel.Visible = true;
                V2WelcomeMessagePanel.ShowPanel = true;
                V2WelcomeMessagePanel.ServerRelativeUrl = ServerRelativeUrl;
                V2WelcomeMessagePanel.ManageUsers = PermissionBitsUsers [ 0 ];
                V2WelcomeMessagePanel.ShowHidePanel ( Constants.PagerEntity.Projects, PermissionBitsProjects );
                pnlProjectsList.Visible = false;
                actionBar.Visible = false;
            }
        }

        protected void lnkShowProjectDetails_Click ( object sender, EventArgs e )
        {
            List<Project> projects = ProjectsModel.GetProjectsForUser (
                SiteCollectionId,
                ServerRelativeUrl,
                CurrentUser,
                new List<ProjectStatus> ( ) { ProjectStatus.Active } );
            ////when viewing the summary details set sort to default
            //V2Pager.SortExpression = "Title";
            //V2Pager.SortDirection = SortDirection.Ascending;

            V2Pager.IsSortClick = true;

            if ( lnkShowProjectDetails.Text == "Show Project Details" )
            {
                lnkShowProjectDetails.Text = "Show Project Summary";
                ProjectSummaryRepeater.Visible = true;
                pnlProjectsList.Visible = false;
            }
            else
            {
                lnkShowProjectDetails.Text = "Show Project Details";
                ProjectSummaryRepeater.Visible = false;
                pnlProjectsList.Visible = true;
            }

            PopulatePage ( );
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsProjects [ 0 ] && !LicenseKeyBits.Contains ( true ) )
            {
                LinkButton btnCreate = new LinkButton ( );
                btnCreate.Text = "Create a new Project";
                btnCreate.Attributes.Add ( "class", "icon-add" );
                btnCreate.Click += new EventHandler ( btnCreate_Click );
                NavigationSub.Commands.Add ( btnCreate );
            }
        }

        protected void btnCreate_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( ServerRelativeUrl + Constants.PortalFileUrls.ProjectNew );
        }

        protected void rptProject_ItemDataBound ( object source, RepeaterItemEventArgs e )
        {
            Project project = ( Project ) e.Item.DataItem;

            PermissionsModel.GetGlobalPermissionBitsForCurrentUser ( project, CurrentUser, SiteCollectionId, ServerRelativeUrl );

            HyperLink lnkProject = ( HyperLink ) e.Item.FindControl ( "lnkProject" );
            if ( lnkProject != null )
            {
                lnkProject.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( project.Title );
                lnkProject.NavigateUrl = project.ServerRelativeWebUrl;
            }

            Literal ltStatus = ( Literal ) e.Item.FindControl ( "ltStatus" );
            if ( ltStatus != null )
            {
                double today = default ( double );
                double shouldBe = default ( double );

                today = Math.Round ( ( project.ActualWork / project.TotalWork ) * 100, 0 );
                today = !Double.IsNaN ( today ) && !Double.IsInfinity ( today ) ? today : 0;

                shouldBe = Math.Round ( ( project.ProjectedWork / project.TotalWork ) * 100, 0 );
                shouldBe = !Double.IsNaN ( shouldBe ) && !Double.IsInfinity ( shouldBe ) ? shouldBe : 0;

                string image = "<img src='{0}' alt='{1}' />";
                if ( ( shouldBe - today ) < 10 )
                    image = string.Format ( image, "/_layouts/images/Kiiro/good.png", "good" );
                else if ( ( shouldBe - today ) < 30 && ( shouldBe - today ) >= 10 )
                    image = string.Format ( image, "/_layouts/images/Kiiro/bad.png", "bad" );
                else
                    image = string.Format ( image, "/_layouts/images/Kiiro/ugly.png", "ugly" );

                ltStatus.Text = @"<div class='timeline'>
                                    <div class='progress'>" +
                                        image +
                                        @"<div id='progressGutter' runat='server' class='progress-gutter'>
                                            <div id='progressBar' runat='server' class='progress-bar' style='width:" + 234 * ( today / 100 ) + @"px'>
                                            </div>
                                        </div>
                                        <h2>" + string.Format ( "{0}%", today.ToString ( ) ) + @"</h2> 
                                    </div>
                                </div>";
            }

            Label lblStartDate = ( Label ) e.Item.FindControl ( "lblStartDate" );
            if ( lblStartDate != null )
            {
                lblStartDate.Text = FormattingHelpers.DateTimeToStringOrDashes ( project.StartDate );
            }

            Label lblEndDate = ( Label ) e.Item.FindControl ( "lblEndDate" );
            if ( lblEndDate != null )
            {
                lblEndDate.Text = FormattingHelpers.DateTimeToStringOrDashes ( project.EndDate );
            }

            //Get Project Manager By ID
            if ( project != null && project.ProjectManagerIds.Count > 0 )
            {
                User projectManager = UserModel.GetUserById ( project.ProjectManagerIds [ 0 ], SiteCollectionId, ServerRelativeUrl );
                if ( projectManager != null )
                {
                    HyperLink lnkProjectManager = ( HyperLink ) e.Item.FindControl ( "lnkProjectManager" );
                    if ( lnkProjectManager != null )
                    {
                        lnkProjectManager.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( projectManager.FullName );
                        lnkProjectManager.NavigateUrl = String.Format ( "{0}{1}?id={2}",
                            ServerRelativeUrl, Constants.PortalFileUrls.UserDisplay, projectManager.SPUserId );
                    }
                }
            }
        }

        protected void ProjectSummaryRepeater_ItemDataBound ( object source, RepeaterItemEventArgs e )
        {
            Kiiro.Common.Entities.Project p = e.Item.DataItem as Kiiro.Common.Entities.Project;

            ProjectSummary v2ProjectSummary = ( ProjectSummary ) e.Item.FindControl ( "v2ProjectSummary" );
            v2ProjectSummary.Project = p;
        }

        #endregion

        #region Pager Related Methods

        private void SortList ( )
        {
            titleSort.Visible = false;
            endSort.Visible = false;
            startSort.Visible = false;

            Literal sortText = titleSort;
            string sortTextTemplate = "<img src='/_layouts/images/Kiiro/icon-sort-{0}.gif' />";

            switch ( V2Pager.SortExpression )
            {
                case "StartDate":
                    sortText = startSort;
                    projects.Sort ( delegate ( Project p1, Project p2 ) { return p1.StartDate.CompareTo ( p2.StartDate ); } );
                    break;
                case "EndDate":
                    sortText = endSort;
                    projects.Sort ( delegate ( Project p1, Project p2 ) { return p1.EndDate.CompareTo ( p2.EndDate ); } );
                    break;
                case "Title":
                default:
                    sortText = titleSort;
                    projects.Sort ( delegate ( Project p1, Project p2 ) { return p1.Title.CompareTo ( p2.Title ); } );
                    break;
            }

            sortText.Visible = true;

            if ( V2Pager.SortDirection == SortDirection.Ascending )
            {
                sortText.Text = string.Format ( sortTextTemplate, "asc" );
            }
            else
            {
                sortText.Text = string.Format ( sortTextTemplate, "desc" );
                projects.Reverse ( );
            }
        }

        private void RePopulatePage ( object sender, EventArgs e )
        {
            PopulatePage ( );
        }

        protected void SortBy_Click ( object sender, EventArgs e )
        {
            LinkButton link = ( LinkButton ) sender;
            if ( V2Pager.SortDirection == SortDirection.Ascending && V2Pager.SortExpression == link.CommandArgument )
                V2Pager.SortDirection = SortDirection.Descending;
            else
                V2Pager.SortDirection = SortDirection.Ascending;
            V2Pager.SortExpression = link.CommandArgument;

            V2Pager.IsSortClick = true;
            V2Pager.DisplayedCount = rptProject.Items.Count;

            PopulatePage ( );
        }

        #endregion
    }

}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.PortalPages/Projects/ActiveProjects.aspx.cs $
 * 
 * 30    2/08/10 2:28p Camerons
 * 
 * 29    2/08/10 12:00p Camerons
 * 
 * 28    1/06/10 12:39p Camerons
 * 
 * 27    12/23/09 3:31p Stefanf
 * 
 * 26    12/07/09 3:16p Stefanf
 * 
 * 25    12/02/09 12:29p Stefanf
 * 
 * 24    10/26/09 9:52a Adamw
 * Case 348
 * 
 * 23    19/10/09 4:56p Shafia
 * Switching between Project Summary and Project Details will now keep the
 * paging and sorting the same
 * 
 * 22    8/10/09 3:27p Camerons
 * 
 * 21    7/10/09 3:01p Camerons
 * 
 * 20    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 19    30/09/09 9:44a Shafia
 * 
 * 18    25/09/09 10:44a Shafia
 * fixed sort method to retain page index and display correct number of
 * rows when sort is clicked.
 * 
 * 17    24/09/09 3:46p Shafia
 * 
 * 16    23/09/09 4:34p Shafia
 * implemented the new WelcomeMessagePanel user control on Projects,
 * Users, CustomLists, Work, Documents, and Discussions pages.
 * Links are being displayed based on PermissionsBits[Entity]
 * 
 * 15    23/09/09 12:21p Shafia
 * 
 * 14    22/09/09 10:29a Shafia
 * 
 * 13    21/09/09 12:42p Shafia
 * 
 * 12    18/09/09 2:33p Shafia
 * New Pager Implemented. All data binding is done on the page itself not
 * on the Pager control
 * 
 * 11    18/09/09 1:12p Camerons
 * 
 * 10    16/09/09 10:50a Shafia
 * 
 * 9     16/09/09 10:19a Shafia
 * implemented the new pager
 * 
 * 8     9/09/09 2:17p Shafia
 * Replaced the project summary control with the new desgin
 * 
 * 7     9/09/09 1:40p Shafia
 * 
 * 6     9/09/09 1:31p Shafia
 * 
 * 5     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/